#pragma once
#include<iostream>
#include<string>
#include<set>
#include"Common.hpp"
#include"InetAddr.hpp"
#include"Log.hpp"
using namespace LogModule;
class Command
{
public:
    Command()
    {
        _WhiteListCommand.insert("ls");
        _WhiteListCommand.insert("pwd");
        _WhiteListCommand.insert("ls -l");
        _WhiteListCommand.insert("ll");
        _WhiteListCommand.insert("touch haha.txt");
        _WhiteListCommand.insert("whoami");
    }
    bool IsSafe(const std::string& cmd)
    {
        auto iter = _WhiteListCommand.find(cmd);
        return iter != _WhiteListCommand.end();
    }
    std::string Execute(const std::string& cmd,InetAddr &peer)
    {
        //1.想执行命令就必须要在白名单里
        if(!IsSafe(cmd))
        {
            return std::string("坏人");
        }
        std::string who = peer.StringAddr();
        //2.执行命令
        FILE *fp = popen(cmd.c_str(),"r");//这个函数会创建一个管道，和一个进程，子进程打开的写端，父进程就是读端.子进程执行命令
        if(fp == nullptr)
        {
            return std::string("你要执行的命令不存在") + cmd;
        }
        std::string res;
        char line[1024];
        while(fgets(line,sizeof(line),fp))
        {
            res += line;
        }
        pclose(fp);
        std::string result = who + "execute done,result is: " + res;
        LOG(LogLevel::DEBUG) <<result;
        
        return result;
    }
    ~Command()
    {}
private:
    std::set<std::string> _WhiteListCommand;

};